﻿namespace Vboot.Core.Module.Bpm;

public class BpmTaskHistService : ITransient
{
    public async Task<BpmTaskHist> CreateTask(BpmTaskMain mainTask)
    {
        BpmTaskHist histTask = new BpmTaskHist();
        histTask.id = mainTask.id;
        histTask.proid = mainTask.proid;
        histTask.state = "20";
        histTask.exman = mainTask.exman;
        histTask.nodid = mainTask.nodid;
        histTask.type = mainTask.type;
        await _repo.InsertAsync(histTask);
        return histTask;
    }
    
    public async Task<List<BpmTaskHist>> CreateTaskList(List<BpmTaskMain> mainTaskList)
    {
        List<BpmTaskHist> list = new List<BpmTaskHist>();
        foreach (BpmTaskMain mainTask in mainTaskList)
        {
            if(mainTask.actag){
                BpmTaskHist histTask = new BpmTaskHist();
                histTask.id = mainTask.id;
                histTask.proid = mainTask.proid;
                histTask.state = "20";
                histTask.exman = mainTask.exman;
                histTask.nodid = mainTask.nodid;
                histTask.type = mainTask.type;
                await _repo.InsertAsync(histTask);
                list.Add(histTask);
            }
        }
        return list;
    }

    public async Task<BpmTaskHist> FindOne(string id)
    {
        return await _repo.GetSingleAsync(t => t.id == id);
    }

    public async Task Delete(string id)
    {
        await _repo.Context.Deleteable<BpmTaskHist>().Where(it => it.id == id).ExecuteCommandAsync();
    }
    
    public async Task DeleteAllByProidNotEnd(string proid) {
        await _repo.Context.Deleteable<BpmTaskHist>()
            .Where(it => it.proid == proid)
            .Where(t=>t.state=="20")
            .ExecuteCommandAsync();
    }


    public async Task Update(BpmTaskHist hist)
    {
        await _repo.Context.Updateable(hist).ExecuteCommandAsync();
    }

    private readonly SqlSugarRepository<BpmTaskHist> _repo;

    public BpmTaskHistService(SqlSugarRepository<BpmTaskHist> repo)
    {
        _repo = repo;
    }
}